package com.yj.spring.charpter05;

import com.yj.spring.beanPostProcessor.BeanPostProcessor;
import com.yj.spring.charpter04.ClassPathXmlApplicationContext;

import java.util.List;

public class AutowireCapableBeanFactory{

    public ClassPathXmlApplicationContext applicationContext;
    public List<BeanPostProcessor> beanPostProcessors;

    public AutowireCapableBeanFactory(ClassPathXmlApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        this.beanPostProcessors.add(beanPostProcessor);
    }

    public void removeBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        this.beanPostProcessors.remove(beanPostProcessor);
    }

    public List<BeanPostProcessor> getBeanPostProcessors() {
        return this.beanPostProcessors;
    }

    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) {
        Object result = existingBean;
        for (BeanPostProcessor beanPostProcessor : this.beanPostProcessors) {
            result = beanPostProcessor.postProcessBeforeInitialization(result, beanName);
            if (result == null){
                return existingBean;
            }
        }
        return result;
    }


    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) {
        Object result = existingBean;
        for (BeanPostProcessor beanPostProcessor : this.beanPostProcessors) {
            result = beanPostProcessor.postProcessAfterInitialization(result, beanName);
            if (result == null){
                return existingBean;
            }
        }
        return result;
    }


}
